const {createMenu, updateMenu, getLeftMenu, getMenuList, deleteMenu} = require('../service/menu.service');
const {setTree} = require('../utils/util')
const { nanoid } = require('nanoid')
class MenuController {
  // 新增菜单
  async addMenu(ctx) {
    // 1、接收参数
    const {pid, name, path, icon, order} = ctx.request.body;
    try {
      const key = nanoid()
      const res = await createMenu({pid, name, path, icon, order, key});

       // 3、返回数据
       ctx.body = {
        code: 200,
        data: {},
        msg: "新增菜单成功",
      }
    } catch(err) {
      console.log(err)
    }
  }
  // 修改菜单
  async editMenu(ctx) {
    // 1、接收参数
    const {id, name, path, icon, order} = ctx.request.body;
    try {
      const res = await updateMenu({id, name, path, icon, order});

       // 3、返回数据
       ctx.body = {
        code: 200,
        data: {},
        msg: "修改菜单成功",
      }
    } catch(err) {
      console.log(err)
    }
  }
  // 删除菜单
  async delMenu(ctx) {
    // 1、接收参数
    const {id} = ctx.request.body;
    try {

      const res = await deleteMenu({id});

       // 3、返回数据
       ctx.body = {
        code: 200,
        data: {},
        msg: "删除菜单成功",
      }
    } catch(err) {
      console.log(err)
    }
  }

  // 查询左侧菜单
  async getMenuData(ctx) {
   
    try {
      const res = await getLeftMenu();

      // 数组转成树
      let data =  setTree(res, 0);

       // 3、返回数据
       ctx.body = {
        code: 200,
        data: {
          result: data
        },
        msg: "查询成功",
      }
    } catch(err) {
      console.log(err)
    }
  }


  // 查询菜单树
  async getMenuTree(ctx) {
   
    try {
      const res = await getMenuList();

      // 数组转成树
      let data =  setTree(res, 0);

       // 3、返回数据
       ctx.body = {
        code: 200,
        data: {
          result: data
        },
        msg: "查询成功",
      }
    } catch(err) {
      console.log(err)
    }
  }

 
}

module.exports = new MenuController()